/**
 * Created by user on 2018/4/16.
 */
const RequestStatus = {
  SUCCESS: 'SUCCESS',
  FAIL: 'FAIL'
}
const ErrorMsg = {
  SUCCESS: 'success',
  SYSTEM_ERROR: 'SYSTEM_ERROR',
  PARSE_ERROR: 'PARSE_ERROR'
}
const formatData = (data) => {
  const formData = new FormData()
  if (data) {
    for (let key in data) {
      formData.append(key, data[key])
    }
  }
  return formData
}
const SendRequest = (url, method, data) => {
  const promise = new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open(method, url, true)
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          let res = {}
          try {
            res = JSON.parse(xhr.response)
            resolve({
              status: RequestStatus.SUCCESS,
              msg: ErrorMsg.SUCCESS,
              data: res
            })
          } catch(e) {
            resolve({
              status: RequestStatus.FAIL,
              msg: ErrorMsg.PARSE_ERROR,
              data: null
            })
          }
        } else {
          resolve({
            status: RequestStatus.FAIL,
            msg: ErrorMsg.SYSTEM_ERROR,
            data: null
          })
        }
      }
    }
    xhr.send(formatData(data))
  })
  return promise
}
const UploadFile = (url, data) => {
  const promise = new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open('POST', url, true)
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
        if(xhr.status == 200) {
          let res = {}
          try {
            res = JSON.parse(xhr.response)
            resolve({
              status: RequestStatus.SUCCESS,
              msg: ErrorMsg.SUCCESS,
              data: res
            })
          } catch(e) {
            resolve({
              status: RequestStatus.FAIL,
              msg: ErrorMsg.PARSE_ERROR,
              data: null
            })
          }
        } else {
          resolve({
            status: RequestStatus.FAIL,
            msg: ErrorMsg.SYSTEM_ERROR,
            data: null
          })
        }
      }
    }
    xhr.send(data)
  })
  return promise
}

module.exports = {
  SendRequest,
  UploadFile,
  RequestStatus,
  ErrorMsg
}
